<template>
  <div>
    <ry-modal title="会员卡" v-model="visible" destroyOnClose
      :confirmLoading="confirmLoading" :ryfooter="null">
      <a-spin :spinning="confirmLoading">
        <a-form-model :model="form" :rules="rules" v-bind="modelConfig">
          <a-row :gutter="[24,0]">
            <a-col :span="24" style="font-weight: 600;margin-bottom: 10px;margin-left: 20px">
              <span style="background-color:#3acaca;margin-right: 4px">&nbsp</span>客户信息
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="名称" :labelCol="{span:6}">
                <span style="color: #00bfbf">{{account.nickname}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="手机号">
                <span style="color: #00bfbf">{{account.phone}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="编码">
                <span style="color: #00bfbf">{{account.serialNumber}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="身份证">
                <span style="color: #00bfbf">{{account.idCard}}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="年龄">
                <span style="color: #00bfbf">{{ moment().diff(moment(account.birth), 'years') + '岁' }}</span>
              </a-form-model-item>
            </a-col>
            <a-col :span="12">
              <a-form-model-item label="性别">
                <span style="color: #00bfbf">{{account.sex}}</span>
              </a-form-model-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24">
              <a-col :span="24" style="font-weight: 600;margin-bottom: 10px;margin-left: 20px">
                <span style="background-color:#3acaca;margin-right: 4px">&nbsp</span>会员卡信息
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="会员卡名称" :labelCol="{span:6}">
                  <span style="color: #00bfbf">{{this.form.cardName}}</span>
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item label="剩余天数">
                  <span v-if="remainingDays > 0" style="color: #00bfbf">{{remainingDays}}天</span>
                  <span v-else>已过期</span>
                </a-form-model-item>
              </a-col>
              <a-table bordered :data-source="projects" :columns="columns">
                <template slot="projectName" slot-scope="text, record">
                  <span>{{$getDictName('APPLY_PROJECT', record.projectName)}}</span>
                </template>
                <template slot="projectPrice" slot-scope="text, record">
                  <span>{{record.projectPrice}} 元</span>
                </template>
                <template slot="quantity" slot-scope="text, record">
                  <span>{{record.quantity}}</span>
                </template>
                <template slot="useQuantity" slot-scope="text, record">
                  <a style="color: #008cbf;text-decoration: underline;" @click="openApplyProjects(record)">{{record.useQuantity}}</a>
                </template>
                <template slot="operation" slot-scope="text, record">
                  <a-button type="primary" :disabled="record.quantity === 0" @click="applyProject(record)">核销</a-button>
                </template>
              </a-table>
            </a-col>
          </a-row>
        </a-form-model>
      </a-spin>
    </ry-modal>
    <a-modal title="核销" :visible="visibleApplyProject" :maskClosable="false" @cancel="handleApplyProjectCancel"
              @ok="handleApplyProjectOk" :confirmLoading="applyProjectLoading">
      <a-form-model>
        <a-row>
          <a-col :span="12">
            <a-form-model-item label="项目名称" :labelCol="{span:8}" :wrapperCol="{span:12}">
              <a-tag color="blue">{{$getDictName('APPLY_PROJECT', record.projectName)}}</a-tag>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="数量" :labelCol="{span:4}" :wrapperCol="{span:12}">
              <a-input-number v-model="form.projectNumber" style="width: 30%;" />
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="实验室" :labelCol="{span:4}" :wrapperCol="{span:12}">
              <a-input v-model="form.accountSource" placeholder="请输入对应实验室"/>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="使用人" :labelCol="{span:4}" :wrapperCol="{span:12}">
              <ry-select :dataSource="businessAccounts" labelKey="nickname" extraLabel="serialNumber" valueKey="id" :showArrow="false" allowClear
                         v-model="form.accountId" :open="!!searchText" @search="onSearch" @select="selectAccount" placeholder="输入客户名称搜索"></ry-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="24">
            <a-form-model-item label="核销备注" :labelCol="{span:4}" :wrapperCol="{span:18}">
              <a-input v-model="form.remake"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </a-modal>
    <a-modal :title="modelTitle + ' 项目使用情况'" :visible="openApplyProjectModel" :maskClosable="true" @cancel="applyProjectModel"
             :confirmLoading="applyProjectLoading" :footer="null" centered width="50%">
      <a-form-model>
        <a-table bordered :data-source="applyProjects" :columns="applyProjectColumns">
          <template slot="projectType" slot-scope="text, record">
            <span>
              {{$getDictName('PROJECT_TYPE', record.projectType)}}
            </span>
          </template>
        </a-table>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import moment from 'moment'
export default {
  props: ['account'],
  data () {
    return {
      count: 0,
      confirmLoading: false,
      visibleApplyProject: false,
      applyProjectLoading: false,
      openApplyProjectModel: false,
      applyProjects: [],
      allApplyProjects: [],
      applyProjectId: '',
      modelTitle: '',
      useAccountName: '本人',
      visible: false,
      remainingDays: '',
      searchText: '',
      form: {},
      record: {},
      projects: [],
      businessAccounts: [],
      modelConfig: {
        ref: 'ruleForm',
        labelCol: { span: 6 },
        wrapperCol: { span: 14 }
      },
      url: {
        byId: this.$api.permission.accountMemberCards.byId,
        apply: this.$api.permission.accountMemberCards.verification
      },
      applyProjectColumns: [
        {
          title: '客户名称',
          dataIndex: 'businessAccount.nickname',
          align: 'center',
        },
        {
          title: '客户编号',
          dataIndex: 'businessAccount.serialNumber',
          align: 'center',
        },
        {
          title: '核销时间',
          dataIndex: 'createTime',
          align: 'center',
        },
        {
          title: '备注',
          dataIndex: 'remake',
          align: 'center',
        },
        {
          title: '是否采样',
          dataIndex: 'projectType',
          align: 'center',
          scopedSlots: { customRender: 'projectType' },
        }
      ],
      columns: [
        {
          title: '项目名称',
          dataIndex: 'projectName',
          width: '30%',
          scopedSlots: { customRender: 'projectName' },
        },
        {
          title: '单价',
          dataIndex: 'projectPrice',
          width: '20%',
          scopedSlots: { customRender: 'projectPrice' },
        },
        {
          title: '剩余数量',
          dataIndex: 'quantity',
          width: '20%',
          scopedSlots: { customRender: 'quantity' },
        },
        {
          title: '已核销数量',
          dataIndex: 'useQuantity',
          width: '20%',
          scopedSlots: { customRender: 'useQuantity' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
        },
      ],
      rules: {
        idCard: [{
          required: true,
          message: '请输入身份证号码',
          trigger: 'change'
        }, { pattern: this.$validate.idCard, trigger: 'change', message: '请输入正确的身份证号码' }],
        cardName: [{
          required: true,
          message: '请输入会员卡名称',
          trigger: 'blur'
        }],
        gender: [{
          required: true,
          message: '请选择性别',
          trigger: 'blur'
        }],
        birth: [{
          required: false
        }]
      }
    }
  },
  created () {

  },
  computed: {

  },
  watch: {

  },
  methods: {
    open (record) {
      this.form = {}
      this.form = { ...record }
      this.visible = true
      this.applyProjectLoading = false
      this.selectProjects()
      this.projects = []
      this.applyProjects = []
      this.allApplyProjects = []
      this.record = {}
      this.form.accountId = ''
      this.$set(this.form, 'projectNumber', 1)
      console.log('AccountMemberCardModel.vue', record)
      this.remainingDays = this.computeDays(this.form.expirationTime)
    },
    onSearch (value) {
      this.searchText = value
      console.log('onSearch', value)
    },
    selectAccount (value) {
      this.searchText = undefined
    },
    applyProject (record) {
      this.record = record
      this.useAccountName = '本人'
      this.visibleApplyProject = true
    },
    handleApplyProjectCancel () {
      this.visibleApplyProject = false
      this.record = {}
    },
    handleApplyProjectOk () {
      this.applyProjectLoading = true
      if (this.form.accountId === '') {
        this.$message.warning('请选择核销人!')
        this.applyProjectLoading = false
        return
      }
      let params = {
        remake: this.form.remake,
        accountId: this.form.accountId,
        id: this.form.id,
        accountMemberCardProjectId: this.record.id,
        projectNumber: this.form.projectNumber,
        accountSource: this.form.accountSource
      }
      this.$post(this.url.apply, params).then(response => {
        if (response.code === 200) {
          this.$message.success('核销成功')
          this.applyProjectLoading = false
          this.selectProjects()
          this.handleApplyProjectCancel()
        }
      })
    },
    selectProjects () {
      this.$get(`${this.url.byId}/${this.form.id}`).then(res => {
        if (res.code === 200) {
          this.projects = res.data.accountMemberProjects
          this.businessAccounts = res.data.businessAccounts
          this.allApplyProjects = res.data.applyProjects
        }
      })
    },
    computeDays (value) {
      // 解析目标日期和当前日期
      const targetDate = new Date(value);
      const today = new Date();
      // 计算差值（毫秒）并转换为天数
      const diffTime = targetDate - today;
      console.log(value, targetDate, today, diffTime)
      // 返回结果
      return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
    },
    openApplyProjects (record) {
      console.log('openApplyProjects', record)
      this.openApplyProjectModel = true
      this.modelTitle = ''
      this.applyProjects = []
      this.modelTitle = this.$getDictName('APPLY_PROJECT', record.projectName)
      // 从this.allApplyProjects数组过滤出applyProject === record.projectName数据赋值到this.applyProjects
      this.applyProjects = this.allApplyProjects.filter(item => item.applyProject === record.projectName)
    },
    applyProjectModel () {
      this.openApplyProjectModel = false
      this.applyProjects = []
      this.modelTitle = ''
    }
  },
  mounted () {
  }
}
</script>

<style scoped>
.ry-modal .body-container .ant-form-item {
  margin-bottom: 0.05rem;
}
.editable-add-btn {
  margin-bottom: 8px;
}
</style>
